package com.moshang.blog.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.entity.SysLog;
import com.moshang.blog.service.SysLogService;
import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.RestResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @program: blog
 * @description: 操作日志
 * @author: xieweiwei
 * @create: 2018-10-19 14:12
 **/
@Controller
@RequestMapping("back/system/sysLog")
public class SysLogController {
    @Autowired
    private SysLogService sysLogService;
    @GetMapping("list")
    public String list(){
        return "back/system/sysLog/list";
    }

    @PostMapping("list")
    @ResponseBody
    public PageUtil<SysLog> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                 @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                 ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        PageUtil<SysLog> pageUtils = new PageUtil<>();
        QueryWrapper<SysLog> wrapper = new QueryWrapper<>();
        if(!map.isEmpty()){
            String keys = (String) map.get("type");
            if(StringUtils.isNotBlank(keys)) {
                wrapper.eq("type", keys);
            }
            String title = (String) map.get("title");
            if(StringUtils.isNotBlank(title)){
                wrapper.like("title",title);
            }
            String username = (String)map.get("username");
            if(StringUtils.isNotBlank(username)){
                wrapper.eq("username",username);
            }
            String httpMethod = (String)map.get("method");
            if(StringUtils.isNotBlank(httpMethod)){
                wrapper.eq("http_method",httpMethod);
            }
        }
        IPage<SysLog> logPage = sysLogService.page(new Page<>(page,limit),wrapper);
        pageUtils.setCount((int) logPage.getTotal());
        pageUtils.setData(logPage.getRecords());
        return  pageUtils;
    }

    @RequiresPermissions("system:logs:delete")
    @PostMapping("delete")
    @ResponseBody
    public RestResponse delete(@RequestParam("ids[]") List<Long> ids){
        if(ids == null || ids.size()==0){
            return RestResponse.failure("id不能为空");
        }
        sysLogService.removeByIds(ids);
        return RestResponse.success();
    }


}
